<?php
session_start();
require_once 'function.php';

$f = $_SERVER['REQUEST_METHOD'];
$a = $_GET['a'];
$b = $_GET['b'];

switch($a)
{
	case 'login':
		switch($b)
		{
			case 'index':
			{
				switch($f)
				{
					case 'GET':
						require_once('./login.html');
						break;
					case 'POST':
						$username = $_POST['username'];
						$password = $_POST['password'];
						$salt = '654gfdoiu091zx';
						$password = md5($username.$password.$salt);

                        $sql = "select * from user where name='$username' and passwd='$password'";

                        $result = query_select($sql);
                        $result = end($result);
                        if (empty($result))
                        {
							alert_json("登陆失败: 用户名或密码错误", '0', "./index.php?a=login&b=index");
                        }
                        else
                        {
							#setcookie('username', $username, time()+3600);
							#setcookie('password', $password, time()+3600);
							$_SESSION['username'] = $username;
							alert_json("登陆成功", '1', "./index.php?a=login&b=index");
                        }

						break;
					default:
						break;
				}
			}
			break;

			case 'register':
				{
					switch($f)
					{
						case 'GET':
							require_once('./register.html');
							break;
						case 'POST':
							$username = $_POST['username'];
							$password = $_POST['password'];

							$sql = "select * from user where name='$username'";
							$result = query_select($sql);
							#var_dump($result);
							if (!empty($result))
							{
								return alert_json("用户名已存在", '0', "./index.php?a=login&b=register");
							}
							
							$salt = '654gfdoiu091zx';
							$password = md5($username.$password.$salt);
							$sql = "insert into user(name, passwd) values('$username', '$password')";
							$result = query($sql);
							if ($result == false)
							{
								alert_json("注册失败", '0', "./index.php?a=login&b=register");
							}
							else
							{
								alert_json("注册成功", '1', "./index.php?a=login&b=index");
							}
							break;
						default:
							break;
					}
				}
				break;


		default:
			break;
		}
		break;
	
	case 'index':
		switch($b)
		{
			case 'index':
				if (empty($_SESSION['username']))
				{
					die(header("Location: ./index.php?a=login&b=index"));
				}
				echo 'hello '.$_SESSION['username'];
				break;
			default:
				break;
		}
		break;
	default:
		break;
}
?>